有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java想将值发送到cmd,不知道命令或如何发送

好的,我有一个问题。请求URL的exe文件,当我在http链接中提示时,它会告诉我网站的标题,感觉就像一个小而简单的脚本,所以我想循环浏览使用此链接的网站列表。exe文件,所以我尝试首先使用批处理文件。但似乎很难通过链接,所以我尝试了powershell,因为我在某个地方读到过,如果我使用击键,应该会更容易,但最终使用java使其更容易。但是,我不明白如何将列表中的链接“发送”到已编译的列表中。exe文件,同时运行。这是我第一次画的

-> start bat-program.
-> ->call for start .exe file 
-> ->wait 2sec or when ready.
-> ->send URL into .exe 
-> ->press enter command
-> ->wait 2sec
-> ->press exit command
-> ->wait 2sec
-> loop....

我能够使用bat或java在cmd或powershell中启动/循环程序,但在应用程序运行时不发送值。。感觉有点傻:(

谢谢你给我的建议,我怎样才能让它工作


共 (1) 个答案

  1. # 1 楼答案

        public class Wrapper {
    
            public static void main(String[] args) throws IOException, InterruptedException {
    
                ExecutorService executor = Executors.newSingleThreadExecutor();
                for (String url : Arrays.asList("google.com/", "github.com/")) {
                    Process process = new ProcessBuilder("compiled.exe").start();
    
                    //process stdin / stderr streams asynchronously.
                    executor.submit(() -> {
                        readStream((String s) -> System.out.println("STDOUT::" + s), process.getInputStream());
                    });
                    executor.submit(() -> {
                        readStream((String s) -> System.out.println("STDERR::" + s), process.getErrorStream());
                    });
    
                    Thread.sleep(2000);//wait 2 sec
                    provideCommandInput(process, url);//url with enter
                    Thread.sleep(2000);//wait 2 sec
                    provideCommandInput(process, "exit");//exit with enter            
                    Thread.sleep(2000);//wait 2 sec
    
                    process.destroy();
                }
                executor.shutdown();
            }
    
            //Read a stream
            public static void readStream(Consumer<String> lineConsumer, InputStream is) {
                try (BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
                    buffer.lines().forEach(lineConsumer);
                } catch (UncheckedIOException | IOException ex) {
                    //broken pipe.
                }
            }
    
            //provide input to the given process
            private static void provideCommandInput(Process proc, String command) throws IOException {
                final String newline = System.lineSeparator();
                proc.getOutputStream().write((command + newline).getBytes());
                proc.getOutputStream().flush();
            }
        }